package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"go-blog-demo/common"
	"go-blog-demo/entity"
	"go-blog-demo/response"
	"go-blog-demo/vo"
)

type IUserController interface {
	ICrudController
}

type UserController struct {
	*gorm.DB
}

func NewUserController() *UserController {
	common.GetDB().AutoMigrate(entity.User{})
	return &UserController{
		common.DB,
	}
}
func (u UserController) Create(context *gin.Context) {
	var newUser entity.User
	if err := context.ShouldBindJSON(&newUser); err != nil {
		response.BadRequest(context, 4000, err.Error(), nil)
		return
	}
	if err := common.ValidatorIns.Struct(newUser); err != nil {
		response.BadRequest(context, 4000, err.Error(), nil)
		return
	}
	newUser.Password = common.HashAndSalt([]byte(newUser.Password))
	if createError := u.DB.Create(&newUser).Error; createError != nil {
		response.BadRequest(context, 4000, createError.Error(), nil)
		return
	}
	response.Success(context, 20001, "success", nil)
}

func (u UserController) Delete(context *gin.Context) {
}

func (u UserController) Update(context *gin.Context) {
}

func (u UserController) Query(context *gin.Context) {
}
func (u UserController) Login(context *gin.Context) {
	//userLoginBind 用来取context中的json数据的
	var userLoginBind vo.UserLoginBind

	// user 用于DB中查询的数据
	var user entity.User

	// 取出 json
	if err := context.ShouldBindJSON(&userLoginBind); err != nil {
		response.BadRequest(context, 4000, err.Error(), nil)
		return
	}
	//根据email 查询是否存在
	if find := common.DB.Where("email = ?", userLoginBind.Email).Find(&user); find.Error != nil {
		response.Success(context, 5001, "登录失败，账号密码错误！", nil)
		return
	}
	//验证密码是否存在
	fmt.Println(user)
	if !common.ValidatePasswords(user.Password, []byte(userLoginBind.Password)) {
		response.Success(context, 5002, "登录失败，账号密码错误！", nil)
		return
	}
	response.Success(context, 2000, "登录成功！", &user)
}
